package com.cy.hui_jie_dan.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class WebSocketServer {
    @Value("${websocket.port:8088}")
    private int port;
    
    @Value("${websocket.path:/ws}")
    private String path;
    
    @Value("${websocket.reader-idle-time:300}")
    private int readerIdleTime;
    
    @Value("${websocket.writer-idle-time:180}")
    private int writerIdleTime;
    
    @Value("${websocket.all-idle-time:600}")
    private int allIdleTime;
    
    @Value("${websocket.worker-threads:8}")
    private int workerThreads;
    
    @Value("${websocket.max-connections:1000}")
    private int maxConnections;
    
    private Channel serverChannel;
    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;

    @Autowired
    private NettyWebSocketHandler webSocketHandler;

    public void start() throws Exception {
        bossGroup = new NioEventLoopGroup(1);
        workerGroup = new NioEventLoopGroup(workerThreads);

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new HttpServerCodec());
                            pipeline.addLast(new ChunkedWriteHandler());
                            pipeline.addLast(new HttpObjectAggregator(65536));
                            pipeline.addLast(new IdleStateHandler(readerIdleTime, writerIdleTime, allIdleTime, TimeUnit.SECONDS));
                            pipeline.addLast(new WebSocketServerProtocolHandler(path, null, true));
                            pipeline.addLast(webSocketHandler);
                        }
                    });

            serverChannel = bootstrap.bind(port).sync().channel();
            log.info("WebSocket服务器已启动 - 端口: {}, 路径: {}, 读空闲时间: {}秒, 写空闲时间: {}秒, 全部空闲时间: {}秒, 最大连接数: {}, 工作线程数: {}", 
                port, path, readerIdleTime, writerIdleTime, allIdleTime, maxConnections, workerThreads);
        } catch (Exception e) {
            log.error("Failed to start WebSocket server", e);
            stop();
            throw e;
        }
    }

    public void stop() {
        if (serverChannel != null) {
            serverChannel.close();
        }
        if (bossGroup != null) {
            bossGroup.shutdownGracefully();
        }
        if (workerGroup != null) {
            workerGroup.shutdownGracefully();
        }
        log.info("WebSocket server stopped");
    }
}